package com.wsm.kotlintest.model.datamodel

import com.wsm.kotlintest.common.isNetworkAvailable
import com.wsm.kotlintest.common.net.BaseObserver
import com.wsm.kotlintest.common.toast
import com.wsm.kotlintest.model.response.BaseResponseModel
import com.wsm.kotlintest.viewmodel.ui.NetStateCallBack
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * Created by 王家宝 on 2018/7/24.
 * TEL:18241150668
 * MAIL:639586819@qq.com
 */
open class BaseModel {
    fun <T> getData(api: Observable<BaseResponseModel<T>>, callback: NetStateCallBack<T>) {
        api
                .subscribeOn(Schedulers.io())
                .doOnSubscribe {
                    if (!isNetworkAvailable()) {
                        if (it != null && !it.isDisposed) {
                            it.dispose()
                        }
                        callback.onNetNotAvailable()
                    }
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BaseObserver<T>() {
                    override fun onHandleSuccess(data: T) {
                        callback.onDataResponse(data)
                    }

                    override fun onHandleError() {
                        "数据异常".toast()
                        callback.onDataError()
                    }

                    override fun onHandleComplete() {
                    }


                })


    }


}